﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xiucai.BPM.Core.Dal;
using Xiucai.Common.Provider;
using Xiucai.Common;
using Xiucai.BPM.Core.Model;

namespace Xiucai.BPM.Core.Bll
{
    public  class AreaBll
    {
        public static AreaBll Instance
        {
            get { return SingletonProvider<AreaBll>.Instance; }
        }
        private IEnumerable<object> GetAreaTreeNodes(int parentid = 0)
        {
            var nodes = AreaDal.Instance.GetChildren(parentid);
            var treeNodes = from n in nodes
                            orderby n.AREA_ID ascending
                            select
                                new { id = n.AREA_ID, text = n.AREA_NAME, children = GetAreaTreeNodes(n.AREA_ID) };
            return treeNodes;
        }
        public IEnumerable<object> GetAreaNodes(int parentid = 0)
        {
            var nodes = AreaDal.Instance.GetChildren(parentid);
            var Nodes = from n in nodes
                            orderby n.AREA_ID ascending
                            select
                                new { id = n.AREA_ID, text = n.AREA_NAME, attributes = new { ulevel = n.AREA_LEVEL }, state = n.AREA_LEVEL < 3 ? "closed" : "open" };
            return Nodes;
        }

        public string GetAreaJson(int parentid = 0)
        {
            var nodes = GetAreaNodes(parentid);
            return JSONhelper.ToJson(nodes);
        }
        public string GetAreaJsonAdd(int parentid = 0, string TEXT = "全部")
        {
            int i=0;
            string n=parentid.ToString();
            if(n.EndsWith("0000"))i=1;
            else if (n.EndsWith("00")) i =2;
            else if(n.Length==6)i=3;
            var nodes = GetAreaNodes(parentid);
            var anodes = new { id = parentid, text = TEXT,attributes = new { ulevel =i }, children = nodes };
            return "["+JSONhelper.ToJson(anodes)+"]";
        }

        public string GetAreaTreeJson(int parentid = 0)
        {
            var nodes = GetAreaTreeNodes(parentid);
            return JSONhelper.ToJson(nodes);
        }
        public string GetAreaTreeJsonAdd( int parentid = 0,int ID = 0, string TEXT = "全部")
        {
            var nodes = GetAreaTreeNodes(parentid);
            var anodes = new { id = ID, text = TEXT, children = nodes };
            return JSONhelper.ToJson(anodes);
        }

        public string GetAreaTreegridData()
        {
            return JSONhelper.ToJson(AreaDal.Instance.GetChildren());
        }

        public bool HasAreaBy(string areaName, int areaid = 0)
        {
            var areas = AreaDal.Instance.GetAll().ToList();
            return areas.Any(n => n.AREA_NAME == areaName && n.AREA_ID != areaid);
        }


    }
}
